 /* BAT_FILE_AUTOMATION
 * BatFile.cs
 * 
 * This program constantly executes batch files given parameters in config.txt
 * and move them to its designated folders.
 * 
 * @author: Brian Jacobe
 * @ver: 5.2
 */

using System;
using System.ComponentModel;
using System.Threading;
using System.Timers;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BAT_FILE_AUTOMATION
{
    public partial class BatFile : Form
    {

        //Store content of config.txt into an array. config.txt is located in bin folder
        string[] textFile = System.IO.File.ReadAllLines("config.txt");

        //Initialize timer
        private System.Timers.Timer progressTimer = new System.Timers.Timer();
        private System.Windows.Forms.Timer constantTimer = new System.Windows.Forms.Timer();

        public BatFile()
        {
            InitializeComponent();
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        /* inputMove()
         * 
         * Checks the input folder and moves each file
         * into the progress folder based on the parameters 
         * in the config.txt
         * 
         */
        private void inputMove()
        {
            int progressLimit = Convert.ToInt32(textFile[1]); //config max value for execution based on config.txt
            string inputPath = textFile[2];                   //pending folder path
            string progressPath = textFile[3];                //progress folder path

            string[] inputFiles = Directory.GetFiles(@textFile[2]);
            string[] fileName = Directory.GetFiles(@textFile[2]).Select(path => Path.GetFileName(path)).ToArray(); //parse only file name
            string[] progressFiles = Directory.GetFiles(@textFile[3]);

            try
            {
                if (progressFiles.Length < progressLimit)
                {
                    int i = 0;
                    string file = progressPath + "\\" + fileName[i];
                    File.Move(inputFiles[i], progressPath + "\\" + fileName[i]);    //Moves file to progress location then performs executeBatch()
                    File.AppendAllText(file, Environment.NewLine + ">NUL move " + "\"" + @file + "\"" + " \"" + @textFile[4] + "\"");
                    Process batchTest1 = Process.Start(file);
                }
                else if (progressFiles.Length == progressLimit)
                {
                    //do nothing
                }
                else if (progressFiles.Length > progressLimit)
                {
                    //do nothing
                }
                       
            }
            catch (Exception e)
            {
                if (e is IndexOutOfRangeException || e is IOException)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        /* constantEvent(Object, EventArgs)
         * 
         * Event handler that will execute constantUpdate() based on timer
         */
        private void constantEvent(Object cObject, EventArgs cEventArgs)
        {
            constantUpdate();
        }

        /* progressEvent(Object, EventArgs)
         * 
         * Event handler that will execute progressCheck() based on timer
         */
        private void progressEvent(Object pObject, EventArgs pEventArgs)
        {
            inputMove();
        }

        /* constantUpdate()
         * 
         * Will constantly update the GUI the number of files
         * within the folders and keep track of the total files executed.
         */
        private void constantUpdate()
        {
            string[] inputFiles = System.IO.Directory.GetFiles(@textFile[2]);
            string[] progressFiles = System.IO.Directory.GetFiles(@textFile[3]);
            string[] completeFiles = System.IO.Directory.GetFiles(@textFile[4]);

            int inputSize = inputFiles.Length;
            int progressSize = progressFiles.Length;
            int completeSize = completeFiles.Length;

            if (inputSize >= 0 || progressSize >= 0 || completeSize >= 0)
            {
                label2.Text = inputSize.ToString();
                label3.Text = progressSize.ToString();
                label4.Text = completeSize.ToString();
            }
            else
            {
                label2.Text = inputSize.ToString();
                label3.Text = progressSize.ToString();
                label4.Text = completeSize.ToString();
            }
        }

        /* button2_Click(object, EventArgs)
         * 
         * On button click, run batch automation system.
         */
        private void button2_Click(object sender, EventArgs e)
        {
            constantTimer.Tick += new EventHandler(constantEvent);
            constantTimer.Interval = 1;                     //constantly executing event every millisecond
            constantTimer.Start();

            backgroundWorker1.RunWorkerAsync();             //invokes the DoWork event
        }

        /* button1_Click(object, EventArgs)
         * 
         * Exit button to close program.
         */
        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            DialogResult exitProgram = MessageBox.Show("Are you sure you want to exit?", "Exiting", MessageBoxButtons.YesNo);
            if (exitProgram == DialogResult.Yes)
            {
                this.Close();
            }
            else
            {
                //Do nothing
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (backgroundWorker1.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                int pTimer = Convert.ToInt32(textFile[0]);
                progressTimer = new System.Timers.Timer(1000);
                progressTimer.Elapsed += new ElapsedEventHandler(progressEvent);
                progressTimer.Interval = pTimer * 1000;
                progressTimer.Enabled = true;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("Batch Automation Canceled");
            }
            else
            {
                MessageBox.Show("Batch Automation Complete");
            }
        }

        private void instructionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Instructions:" + "\n" + "1) Create a pending, in_progress, and done folder." + "\n" + "\n" + "2) Copy the path locations for each folder and place them within the config.txt respectively."
                + "\n" + "\n" + "3) Change the values within the config.txt according to requirements." + "\n" + "\n" + "    Line 1: check timer value in seconds" + "\n" + "    Line 2: number of batch to execute" + "\n"
                + "    Line 3: pending path location" + "\n" + "    Line 4: in_progress path location" + "\n" + "    Line 5: done path location" + "\n" + "    Line 6: delay timer value in seconds" + "\n" + "\n"
                + "4) Move the batch files to the pending folder and click on Run to execute the program");
        }
    }
}